<template>
    <BPTable ref='tableRef' align='center' row-key='id' :columns='columns' :api='pageApi' :buttons='buttons' :rowSelection="true" @selectionChange="selectionChange">

        <template #$selection>
            <a-button @click="registerToAli" type="primary">注册到阿里云</a-button>
            <a-button @click="openBindMerchant" type="primary">绑定商户</a-button>
            <a-button @click="unbindMerchant">解绑商户</a-button>
        </template>

        <template #connectStatus="{record}">
            <a-tag v-if="record.connectStatus" :bordered="false" color="success">在线</a-tag>
            <a-tag v-else :bordered="false" color="error">离线</a-tag>
        </template>
        
        <template #enable='{record}'>
            <a-tag v-if='record.enable' color='#87d068'>{{$t('enable')}}</a-tag>
            <a-tag v-else>{{$t('disable')}}</a-tag>
        </template>

        <template #$action="{record}">
            <BTextButton @click="openDelDevice(record)" type="error">删除</BTextButton>
        </template>
    </BPTable>

    <BDrawer v-model:visible='visible' :title='dialogTitle' width='600px' :confirm='submit'>
        <Edit :row="currentRow" ref="formRef" />
    </BDrawer>

    <BDrawer v-model:visible='visibleBindMerchant' title='绑定商户' width='600px' :confirm='submitBindMerchant'>
        <a-form ref="bindMerchantFormRef" :model='bindMerchantFormData'>
            <a-form-item label="商户" name="merchantId" :rules="[{required : true, message : '请选择商户'}]">
                <FetchSelect v-model="bindMerchantFormData.merchantId" allowClear label-field="name" value-field="id" options-field="children" :fetch="queryMerchantApi" />
            </a-form-item>
        </a-form>
    </BDrawer>


    <a-modal v-model:open="delDeviceOpen" @ok="delDevice">
        <template #title>
            <div style="display: flex; align-items: center;"><ExclamationCircleOutlined style="color: #faad14;font-size: 22px;margin-inline-end: 12px;" />确定删除该设备吗</div>
        </template>
        <div class="m-t-10"><a-checkbox v-model:checked="syncDelAli">同时从阿里云删除</a-checkbox></div>
    </a-modal>
</template>

<script lang='ts' setup>
    import { ref } from "vue";
    import { deviceTypeOptionsApi } from '@/api/devices/DeviceType';
    import { bindMerchantApi, deleteApi, pageApi, registerToAliApi, unbindMerchantApi } from '@/api/devices/Device'
    import { parseTime, recursionFn } from "@/utils";
    import { useResourceStore } from "@/store/resource";
    import Edit from './Edit.vue';
    import { Modal, message } from "ant-design-vue";
    import { useI18nStore } from "@/store/i18n";
    import QrCode from '@/components/QrCode.vue'
    import FetchSelect from '@/components/FetchSelect.vue'
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { queryMerchantApi } from '@/api/Merchant';


    


    //多选操作
    const selectedKeys = ref<number[]>([])
    function selectionChange(keys:any[], rows:any[]) {
        selectedKeys.value = keys
    }

    function registerToAli() {
        if(selectedKeys.value.length > 100) {
            message.error('单次不可超过100台设备')
            return
        }

        const handle = (res) => {
            if(res.success) {
                message.success('注册成功')
                tableRef.value.load()
            }else {
                message.error(res.msg)
            }
        }


        Modal.confirm({
            title : '确定注册到阿里云吗',
            async onOk() {
                const res = await registerToAliApi(selectedKeys.value)
                if(selectedKeys.value.length == 1) {
                    handle(res)
                }else {
                    await (new Promise((resolve, reject) => {
                        setTimeout(() => {
                            resolve(null)
                        }, 5000)
                    }))

                    handle(res)
                }

            
                
            }
        })
    }


    //绑定商户
    const visibleBindMerchant = ref(false)
    const bindMerchantFormRef = ref()
    const bindMerchantFormData = ref({
        merchantId : ''
    })
    function openBindMerchant() {
        bindMerchantFormData.value.merchantId = ''
        visibleBindMerchant.value = true
    }
    async function submitBindMerchant() {
        let params  = await bindMerchantFormRef.value.validate()
        const res = await bindMerchantApi(params.merchantId, selectedKeys.value)
        if(res.success) {
            tableRef.value.load()
            visibleBindMerchant.value = false
            message.success('绑定成功')
        }else {
            Modal.error({
                title : res.msg
            })
        }
    }

    async function unbindMerchant() {
        Modal.confirm({
            title : '确定解绑吗',
            async onOk() {
                const res = await unbindMerchantApi(selectedKeys.value)
                if(res.success) {
                    message.success(i18n.t('解绑成功'))
                    tableRef.value.load()
                }else {
                    message.error(res.msg)
                }
            }
        })
    }

    //删除设备
    const delDeviceOpen = ref(false)
    const syncDelAli = ref(true)
    function openDelDevice(row) {
        syncDelAli.value = true
        currentRow.value = row
        delDeviceOpen.value = true
    }
    async function delDevice() {
        const res = await deleteApi(currentRow.value.id, syncDelAli.value)
        if(res.success) {
            delDeviceOpen.value = false
            message.success(i18n.t('deleteSuccess'))
            tableRef.value.load()
        }else {
            message.error(res.msg)
        }
    }


    const i18n = useI18nStore()
    const resourceStore = useResourceStore()

    const visible = ref(false)
    const formRef = ref()
    const dialogTitle = ref()
    const currentRow = ref<any>()

    const tableRef = ref()


    const buttons = ref<SearchButton[]>([])

    if(resourceStore.hasPermission("user:teacher:add")) {
        buttons.value.push({
            button : 'add',
            func : () => {
                currentRow.value = null
                dialogTitle.value = '新增'
                visible.value = true
            }
        })
    }


    const columns = ref<Column[]>([
        {
            dataIndex : 'id',
            title : '设备号',
            inSearch : true,
            placeholder : '多个设备号用,分割'
        },

        {
            dataIndex : 'name',
            title : '名称',
            inSearch : true,
        },

        {
            dataIndex : 'deviceTypeId',
            title : '设备类型',
            customRender({record}) {
                return record.deviceType ? record.deviceType.name : ''
            },

            inSearch : true,
            type : 'treeSelect',
            valueField : 'id',
            labelField : 'name',
            async options() {
                const r = await deviceTypeOptionsApi()
                return recursionFn(r.data, 0, 'id', 'parentId', 'children')
            }
        },

        {
            title : '链接状态',
            dataIndex : 'connectStatus',
            align : 'center',
            inSearch : true,
            type : 'select',
            options : [
                {value : 1, label : '在线'},
                {value : 0, label : '离线'}
            ]
        },

        {
            dataIndex : 'merchant',
            title : '所属商户',
            customRender({text}) {
                return text ? text.name : ''
            },
            inSearch : true,
            name : 'merchantId',
            type : 'fetchSelect',
            valueField : 'id',
            labelField : 'name',
            fetchApi : queryMerchantApi
        },


        {
            title : i18n.t('enable'),
            dataIndex : 'enable',
            align : 'center',
        },
        
        // {
        //     title : '最近登录',
        //     dataIndex : 'lastLoginTime',
        //     align : 'center',
        //     customRender({text}) {
        //         return parseTime(text)
        //     }
        // },

        {
            title : i18n.t('operation'),
            dataIndex : '$action',
            align : 'center',
            $edit : resourceStore.hasPermission('device:update') ? (row) => {
                dialogTitle.value = i18n.t('edit')
                currentRow.value = row
                visible.value = true
            } : undefined,

            // $delete : resourceStore.hasPermission('device:delete') ? async (row) => {
            //     const res = await deleteApi(row.id)
            //     if(res.success) {
            //         message.success(i18n.t('deleteSuccess'))
            //         tableRef.value.load()
            //     }else {
            //         message.error(res.msg)
            //     }
            // } : undefined
        }
    ])

    const dataRows = ref<any[]>([])

    function update(row) {
            dialogTitle.value = i18n.t('edit')
            currentRow.value = row
            visible.value = true
    }

    async function del(row) {
        Modal.confirm({
            title : i18n.t('confirmDel', [row.name]),
            async onOk() {
                const res = await deleteApi(row.id)
                if(res.success) {
                    message.success(i18n.t('deleteSuccess'))
                    tableRef.value.load()
                }else {
                    message.error(res.msg)
                }
            }
        })
            
    }

    async function submit() {
        const res = await formRef.value.submit()
        if(res.success) {
            tableRef.value.reload()
            visible.value = false
            message.success('保存成功')
        }else {
            Modal.error({
                title : res.msg
            })
        }
    }
    
</script>